package com.java80.littlegame.common.service.user;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.java80.littlegame.common.orm.mapper.UUserInfoMapper;
import com.java80.littlegame.common.orm.model.UUserInfo;
import com.java80.littlegame.common.orm.utils.SqlSessionUtils;
import com.java80.littlegame.common.util.MD5Utils;

public class UserService {
	private UserService() {
	}

	private static UserService ins = new UserService();

	public static UserService getInstance() {
		return ins;
	}

	public UUserInfo login(String loginName, String password) {
		UUserInfo u = new UUserInfo();
		u.setLoginName(loginName);
		try {
			u.setPassword(MD5Utils.md5hex32(password));
		} catch (Exception e) {
			e.printStackTrace();
		}
		SqlSession session = null;
		try {
			session = SqlSessionUtils.getSqlSession(true);
			UUserInfoMapper mapper = session.getMapper(UUserInfoMapper.class);
			List<UUserInfo> list = mapper.seleteAccuracy(u);
			if (list != null && list.size() == 1) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SqlSessionUtils.closeSqlSession(session);
		}
		return null;
	}

	public UUserInfo findByLoginName(String loginName) {
		UUserInfo u = new UUserInfo();
		u.setLoginName(loginName);
		SqlSession session = null;
		try {
			session = SqlSessionUtils.getSqlSession(true);
			UUserInfoMapper mapper = session.getMapper(UUserInfoMapper.class);
			List<UUserInfo> list = mapper.seleteAccuracy(u);
			if (list != null && list.size() >= 1) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SqlSessionUtils.closeSqlSession(session);
		}
		return null;
	}

	public void register(UUserInfo info) {
		SqlSession session = null;
		try {
			session = SqlSessionUtils.getSqlSession(true);
			UUserInfoMapper mapper = session.getMapper(UUserInfoMapper.class);
			mapper.insert(info);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SqlSessionUtils.closeSqlSession(session);
		}
	}

	public UUserInfo findByUserId(long userId) {
		SqlSession session = null;
		try {
			session = SqlSessionUtils.getSqlSession(true);
			UUserInfoMapper mapper = session.getMapper(UUserInfoMapper.class);
			UUserInfo info = new UUserInfo();
			info.setId(userId);
			return mapper.getById(info);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SqlSessionUtils.closeSqlSession(session);
		}
		return null;
	}
}
